/*!
 * tykhome - soft.js
 * Author tykhome <yongketian@gmail.com>
 */

/**
 * Module dependencies.
 */
var Soft = require('../proxy').Soft;
var SoftTag = require('../proxy').SoftTag;
var Tag = require('../proxy').Tag;
var Notify = require('../proxy').Notify;

var constants = require('../constants');

var Util = require('../libs/util');
var EventProxy = require('eventproxy');
var PAGE = 10;

var Page = function (start, pageSize, data) {
	this.DEFAULT_PAGE_SIZE = PAGE;
	this.start = start;
	this.pageSize = pageSize;
	this.next = data.length > pageSize;
	this.data = data.slice(0, pageSize);
};


/**
 * Show soft list page.
 *
 * @param  {HttpRequest} req
 * @param  {HttpResponse} res
 * @param {Function} next
 */
exports.list = function (req, res, next) {
	// console.log('soft.list');
	var start = parseInt(req.query.start, 10) || 0;
	var end = start + PAGE;

	var proxy = EventProxy.create('softs', 'tags',
		function (page, tags) {
			res.render('soft/index', {
				page: page,
				tags: tags
			});
		});
	proxy.fail(next);

	var fields = {
		html: 0,
		content: 0
	};
	var opt = {
		skip: start,
		limit: PAGE + 1,
		sort: {
			create_at: -1
		}
	};
	Soft.getSoftsByQuery({}, fields, opt, proxy.done('softs', function (softs) {
		var page = new Page(start, PAGE, softs);
		return page;
	}));

	var query = {
		soft_count: {
			'$gte': 2
		}
	};
	var options = {
		sort: {
			soft_count: -1
		}
	};
	Tag.getTagsByQuery(query, {}, options, proxy.done('tags'));
};

/**
 * Show soft view page.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.view = function (req, res, next) {
	console.log('soft.view');
	var id = req.params.id;
	if (id.length !== 24) {
		return res.render('notify/notify', {
			error: '此话题不存在或已被删除。'
		});
	}

	// 扩展使用
	var events = ['soft'];
	var ep = EventProxy.create(events, function (soft) {
		res.render('soft/view', {
			soft: soft
		});
	});

	ep.fail(next);

	Soft.getFullSoft(id, ep.done(function (message, soft, author, tags) {
		if (message) {
			ep.unbind();
			return res.render('notify/notify', {
				error: message
			});
		}

		soft.visit_count += 1;
		soft.save();

		// format date
		soft.friendly_create_at = Util.format_date(soft.create_at, true);
		soft.friendly_update_at = Util.format_date(soft.update_at, true);

		soft.author = author;

		soft.tags = tags;

		ep.emit('soft', soft);
	}));

};

/**
 * Show soft create page.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.showCreateForm = function (req, res, next) {
	console.log('soft.showCreateForm');
	res.render('soft/create');
};

/**
 * create soft.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.create = function (req, res, next) {
	console.log('soft.create');
	var title = req.body.title.trim();
	var abstract = req.body.abstract;
	var content = req.body.content;
	var html = '';
	var tags = [];
	if (req.body.tags !== '') {
		tags = req.body.tags.split(',');
		tags = Util.arr_distinct(tags);
	}

	var edit_error =
		title === '' ?
		'标题不能是空的。' :
		(title.length >= 10 && title.length <= 100 ? '' : '标题字数太多或太少。');

	if (edit_error) {
		res.render('soft/create', {
			tags: tags,
			edit_error: edit_error,
			title: title,
			abstract: abstract,
			content: content
		});
	} else {
		Soft.newAndSave(title, abstract, content, html, req.session.user._id, function (err, soft) {
			if (err) {
				return next(err);
			}

			if (!soft) {
				res.render('soft/create', {
					tags: tags,
					edit_error: '保存失败。',
					title: title,
					abstract: abstract,
					content: content
				});
			}

			// 处理标签
			var proxy = new EventProxy();
			var render = function () {
				res.redirect('/soft/' + soft._id);
			};

			proxy.all('tags_saved', render);
			if (tags.length === 0) {
				proxy.emit('tags_saved');
			}
			var tags_saved_done = function () {
				proxy.emit('tags_saved');
			};
			// after重复异步协作 重复保存
			proxy.after('tag_saved', tags.length, tags_saved_done);
			//save soft tags
			tags.forEach(function (tag_name) {
				if (tag_name.trim() !== '') {
					Tag.updateCount(tag_name.trim(), function (err, tag) {
						SoftTag.newAndSave(soft._id, tag._id, proxy.done('tag_saved'));
					});
				} else {
					proxy.emit('tag_saved');
				}
			});

		});
	}
};

/**
 * Show soft update page.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.showUpdateForm = function (req, res, next) {
	console.log('soft.showUpdateForm');
	var id = req.params.id;
	if (id.length !== 24) {
		return res.render('notify/notify', {
			error: '此话题不存在或已被删除。'
		});
	}

	var events = ['soft', 'tags'];
	var ep = EventProxy.create(events, function (soft, tags) {
		res.render('soft/create', {
			tags: tags,
			id: soft._id,
			title: soft.title,
			abstract: soft.abstract,
			content: soft.content
		});
	});

	ep.fail(next);

	Soft.getSoft(id, ep.done(function (soft) {
		if (!soft) {
			ep.unbind();
			return res.render('notify/notify', {
				error: '此话题不存在或已被删除。'
			});
		}
		ep.emit('soft', soft);

		SoftTag.getSoftTagBySoftId(soft._id, ep.done(function (soft_tags) {
			if (!soft_tags) {
				ep.emit('tags', []);
				return;
			}
			var tagIds = [];
			soft_tags.forEach(function (soft_tag) {
				tagIds.push(soft_tag.tag_id)
			});
			Tag.getTagsByIds(tagIds, ep.done(function (tags) {
				if (!tags) {
					ep.emit('tags', []);
					return;
				}
				var tagNames = [];
				tags.forEach(function (tag) {
					tagNames.push(tag.name);
				});
				ep.emit('tags', tagNames);
			}));
		}));
	}));

};

/**
 * update soft.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.update = function (req, res, next) {
	console.log('soft.update');

	if (!req.session.user) {
		res.redirect('/soft');
		return;
	}

	var id = req.params.id;
	if (id.length !== 24) {
		return res.render('notify/notify', {
			error: '此话题不存在或已被删除。'
		});
	}

	Soft.getSoftById(id, function (err, soft) {
		if (err) {
			return next(err);
		}
		if (!soft) {
			res.render('notify/notify', {
				error: '此话题不存在或已被删除。'
			});
			return;
		}

		if (String(soft.author_id) === req.session.user._id) {
			var title = req.body.title.trim();
			var abstract = req.body.abstract;
			var content = req.body.content;
			var tags = [];
			if (req.body.tags !== '') {
				tags = req.body.tags.split(',');
			}
			var edit_error =
				title === '' ?
				'标题不能是空的。' :
				(title.length >= 10 && title.length <= 100 ? '' : '标题字数太多或太少。');
			if (edit_error) {
				res.render('soft/create', {
					edit_error: edit_error,
					id: id,
					title: title,
					abstract: abstract,
					content: content,
					tags: tags
				});
			} else {
				var ep = new EventProxy();
				var render = function () {
					res.redirect('/soft/' + soft._id);
				};
				ep.all('soft_update', 'tags_removed_done', 'tags_saved_done', render);
				ep.fail(next);

				soft.title = title;
				soft.abstract = abstract;
				soft.content = content;
				soft.html = '';
				soft.update_at = new Date();

				soft.save(ep.done(function () {
					ep.emit('soft_update');

					var tags_removed_done = function () {
						ep.emit('tags_removed_done');
					};
					//删除旧的soft_tag
					SoftTag.getSoftTagBySoftId(soft._id, ep.done(function (soft_tags) {
						if (!soft_tags) {
							ep.emit('tags_removed_done');
						} else {
							ep.after('tag_removed', soft_tags.length, tags_removed_done);
							soft_tags.forEach(function (soft_tag) {
								soft_tag.remove(ep.done(function () {
									Tag.getTagById(soft_tag.tag_id, ep.done(function (tag) {
										ep.emit('tag_removed');
										if (tag) {
											tag.soft_count -= 1;
											tag.save();
										}
									}))
								}));
							});
						}
					}));

					// 保存新的tags
					if (tags.length === 0) {
						ep.emit('tags_saved_done');
					}
					var tags_saved_done = function () {
						ep.emit('tags_saved_done');
					};
					// after重复异步协作 重复保存
					ep.after('tag_saved', tags.length, tags_saved_done);
					//save soft tags
					tags.forEach(function (tag_name) {
						if (tag_name.trim() !== '') {
							Tag.updateCount(tag_name.trim(), ep.done(function (tag) {
								SoftTag.newAndSave(soft._id, tag._id, ep.done('tag_saved'));
							}));
						} else {
							ep.emit('tag_saved');
						}
					});

				}));
			}
		} else {
			res.render('notify/notify', {
				error: '对不起，你不能编辑此话题。'
			});
		}
	});

};

/**
 * Show delete update page.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.showDeleteForm = function (req, res, next) {
	console.log('soft.showDeleteForm');

	res.writeHead(200, {
		'Content-Type': 'text/plain'
	});
	res.end('soft.showDeleteForm\n');
};

/**
 * Delete soft.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.delete = function (req, res, next) {
	console.log('soft.delte');

	if (!req.session.user) {
		res.redirect('/soft');
		return;
	}

	var id = req.params.id;
	if (id.length !== 24) {
		return res.send({
			success: false,
			error: '此话题不存在或已被删除。'
		});
	}

	Soft.getSoftById(id, function (err, soft) {
		if (err) {
			return next(err);
		}
		if (!soft) {
			return res.send({
				success: false,
				error: '此话题不存在或已被删除。'
			});
		}

		if (String(soft.author_id) === req.session.user._id) {
			var ep = new EventProxy();
			var render = function () {
				res.send({
					success: true,
					message: '话题已被删除。'
				});
			};
			ep.all('soft_delete', 'tags_removed_done', render);
			ep.fail(next);

			soft.remove(ep.done(function () {
				ep.emit('soft_delete');

				var tags_removed_done = function () {
					ep.emit('tags_removed_done');
				};
				//删除旧的soft_tag
				SoftTag.getSoftTagBySoftId(soft._id, ep.done(function (soft_tags) {
					if (!soft_tags) {
						ep.emit('tags_removed_done');
					} else {
						ep.after('tag_removed', soft_tags.length, tags_removed_done);
						soft_tags.forEach(function (soft_tag) {
							soft_tag.remove(ep.done(function () {
								Tag.getTagById(soft_tag.tag_id, ep.done(function (tag) {
									ep.emit('tag_removed');
									if (tag) {
										tag.soft_count -= 1;
										tag.save();
									}
								}))
							}));
						});
					}
				}));

			}));
		} else {
			return res.send({
				success: false,
				message: '无权限'
			});
		}
	});
};


/**
 * Delete softs.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.deleteInBatch = function (req, res, next) {
	console.log('soft.deleteInBatch');

	res.writeHead(200, {
		'Content-Type': 'text/plain'
	});
	res.end('soft.deleteInBatch\n');
};

/**
 * 下载链接无效通知
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.message = function (req, res, next) {
	var soft_id = req.body.soft;
	var to_user = req.body.author;
	if (soft_id.length !== 24) {
		return res.send({
			success: false,
			message: '此话题不存在或已被删除。'
		});
	}

	Notify.getSoftLostNotify(soft_id, function (err, notify) {
		if (err) return next(err);
		if (!notify) {
			Notify.newAndSave(constants.notify.type.SOFTLINKLOSE,
				null, to_user, soft_id, function (notify) {
					return res.send({
						success: true,
						message: 'OK'
					});
				});
		} else {
			return res.send({
				success: true,
				message: 'OK'
			});
		}
	});

};